﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using Teamwish.Utilities;

namespace Investment.Common
{
    public class WeChatHelper
    {
        public static string GetAccessToken(string appid, string secret)
        {
            string access_token = Redis.RedisHelper.Get<string>("access_token_" + appid);
            if (string.IsNullOrEmpty(access_token))
            {
                string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
                string response = RequestHelper.HttpGet(string.Format(url, appid, secret));

                JToken token = response.JsonToEntity<JToken>();
                if (token != null)
                {
                    access_token = token.Value<string>("access_token");
                    int expires_in = token.Value<int>("expires_in");
                    Redis.RedisHelper.Set("access_token_" + appid, access_token, DateTime.Now.AddSeconds(expires_in));
                }
            }
            return access_token;
        }

        public static Dictionary<string, string> GetOpenId(string appid, string secret, string code)
        {
            Dictionary<string, string> ht = new Dictionary<string, string>();            
            string url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
            url = string.Format(url, appid, secret, code);
            string response = RequestHelper.HttpGet(url);
            JToken token = response?.JsonToEntity<JToken>();
            if (token != null)
            {
                int errcode = token.Value<int>("errcode");
                if (errcode != 0)
                {
                    LogFactory.GetLogger("loginfo").Error("获取授权失败"+"  appid:" + appid);              
                    return null;
                }            
                string openid = token.Value<string>("openid");
                string unionid = token.Value<string>("unionid");               
                ht["openid"] = openid;
                ht["unionid"] = unionid;
                if (string.IsNullOrEmpty(openid))
                {
                    // 
                }
            }
            return ht;
        }

        public static WechatUserInfo GetUserInfo(string appid, string secret, string code)
        {
            Dictionary<string, string> token = GetOpenId(appid, secret, code);
            if (token != null)
            {
                string accesstoken = GetAccessToken(appid, secret);// token["access_token"];
                string openid = token["openid"];
                string url = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
                url = string.Format(url, accesstoken, openid);
                string strUserInfo = RequestHelper.HttpGet(url);
                try
                {
                    WechatUserInfo userinfo = strUserInfo?.JsonToEntity<WechatUserInfo>();
                    return userinfo;
                }
                catch (Exception)
                {
                    LogFactory.GetLogger("loginfo").Error(strUserInfo);
                    //Logger.LogHelper.Logger.Write(strUserInfo);
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        //public static string GetJSAPI_Ticket(string appid, string secret)
        //{
        //    string ticket = Redis.RedisHelper.Get<string>("jsapi_ticket_" + appid);
        //    if (string.IsNullOrEmpty(ticket))
        //    {
        //        string accesstoken = GetAccessToken(appid, secret);
        //        string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
        //        string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //        JToken token = response.JsonToEntity<JToken>();
        //        if (token != null)
        //        {
        //            ticket = token.Value<string>("ticket");
        //            int expires_in = token.Value<int>("expires_in");
        //            Redis.RedisHelper.Set("jsapi_ticket_" + appid, ticket, DateTime.Now.AddSeconds(expires_in));
        //        }
        //    }
        //    return ticket;
        //}

        //public static string GetJSAPI_Ticket(int tenantid, string accesstoken)
        //{
        //    string ticket = redis.Get("jsapi_ticket_" + tenantid);
        //    if (string.IsNullOrEmpty(ticket))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
        //        string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //        JToken token = response.JsonToEntity<JToken>();
        //        if (token != null)
        //        {
        //            ticket = token.Value<string>("ticket");
        //            int expires_in = token.Value<int>("expires_in");
        //            redis.Set("jsapi_ticket_" + tenantid, ticket, DateTime.Now.AddSeconds(expires_in));
        //        }
        //    }
        //    return ticket;
        //}


        //public static bool FollowPublic(string access_token, string openid)
        //{
        //    Dictionary<string, string> ht = new Dictionary<string, string>();
        //    string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
        //    url = string.Format(url, access_token, openid);
        //    string response = RequestHelper.HttpGet(url);
        //    JToken token = response?.JsonToEntity<JToken>();
        //    if (token != null)
        //    {
        //        int subscribe = token.Value<int>("subscribe");
        //        if (subscribe == 1)
        //        {
        //            return true;
        //        }
        //        else
        //        {
        //            return false;
        //        }
        //    }
        //    else
        //    {
        //        return false;
        //    }
        //}

        //public static Dictionary<string, string> GetJsOpenid(string appid, string secret, string code)
        //{
        //    Dictionary<string, string> ht = new Dictionary<string, string>();

        //    string url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        //    url = string.Format(url, appid, secret, code);
        //    string response = RequestHelper.HttpGet(url);
        //    //Logger.LogHelper.Logger.Write("GetJsOpenid_" + response);
        //    JToken token = response?.JsonToEntity<JToken>();
        //    if (token != null)
        //    {
        //        string session_key = token.Value<string>("session_key");
        //        string openid = token.Value<string>("openid");
        //        string unionid = token.Value<string>("unionid");

        //        string errcode = token.Value<string>("errcode");
        //        string errmsg = token.Value<string>("errmsg");

        //        ht["session_key"] = session_key;
        //        ht["openid"] = openid;
        //        ht["unionid"] = unionid;

        //        ht["errcode"] = errcode;
        //        ht["errmsg"] = errmsg;
        //    }
        //    return ht;
        //}


        //public static string GetConditionalMenu(string appid, string secret)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}";
        //        string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //        return response;
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}
        //public static string GetConditionalMenu(string accesstoken)
        //{
        //    string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}";
        //    string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //    return response;
        //}


        //public static string GetMenu(string appid, string secret)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}";
        //        string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //        return response;
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}

        //public static string GetMenu(string accesstoken)
        //{
        //    string url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}";
        //    string response = RequestHelper.HttpGet(string.Format(url, accesstoken));
        //    return response;
        //}

        //public static string CreateMenu(string appid, string secret, string menu)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}";

        //        string response = RequestHelper.HttpPostJson(string.Format(url, accesstoken), menu);
        //        return response;
        //    }
        //    else
        //    {
        //        return "";
        //    }
        //}

        //public static string CreateMenu(string accesstoken, string menu)
        //{
        //    string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}";

        //    string response = RequestHelper.HttpPostJson(string.Format(url, accesstoken), menu);
        //    return response;
        //}

        //public static void AddMedia(string appid, string secret, string mediaurl, string type)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        //分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
        //        string url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
        //        WebRequest myrequest = WebRequest.Create(mediaurl);
        //        WebResponse myresponse = myrequest.GetResponse();
        //        Stream imgstream = myresponse.GetResponseStream();
        //        byte[] bytes = StreamExtension.StreamToBytes(imgstream);
        //        var data = new WebClient().UploadData(url, bytes);
        //    }
        //}


        //public static string CreateQRCode(string appid, string secret)
        //{
        //    try
        //    {
        //        string accesstoken = GetAccessToken(appid, secret);
        //        string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";
        //        Dictionary<string, object> dic = new Dictionary<string, object>();
        //        dic.Add("action_name", "QR_LIMIT_SCENE");
        //        Dictionary<string, object> dicdetail = new Dictionary<string, object>();

        //        Dictionary<string, string> dicscene = new Dictionary<string, string>();
        //        dicscene.Add("scene_id", "100000");
        //        dicdetail.Add("scene", dicscene);

        //        dic.Add("action_info", dicdetail);
        //        if (!string.IsNullOrEmpty(accesstoken))
        //        {
        //            string response = RequestHelper.HttpPostJson(string.Format(url, accesstoken), dic.ToJsonString());

        //            JToken token = response.JsonToEntity<JToken>();
        //            if (string.IsNullOrEmpty(token.Value<string>("errcode")))
        //            {
        //                var ticket = token.Value<string>("ticket");
        //                if (ticket != "")
        //                {
        //                    return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        //                }
        //                else
        //                {
        //                    return string.Empty;
        //                }
        //            }
        //            else
        //            {
        //                return string.Empty;
        //            }
        //        }
        //        else
        //        {
        //            return string.Empty;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //Logger.LogHelper.Logger.Write(ex);
        //        return string.Empty;
        //    }
        //}

        //public static string CreateQRCode(string accesstoken)
        //{
        //    try
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}";
        //        Dictionary<string, object> dic = new Dictionary<string, object>();
        //        dic.Add("action_name", "QR_LIMIT_SCENE");
        //        Dictionary<string, object> dicdetail = new Dictionary<string, object>();

        //        Dictionary<string, string> dicscene = new Dictionary<string, string>();
        //        dicscene.Add("scene_id", "100000");
        //        dicdetail.Add("scene", dicscene);

        //        dic.Add("action_info", dicdetail);
        //        if (!string.IsNullOrEmpty(accesstoken))
        //        {
        //            string response = RequestHelper.HttpPostJson(string.Format(url, accesstoken), dic.ToJsonString());

        //            JToken token = response.JsonToEntity<JToken>();
        //            if (string.IsNullOrEmpty(token.Value<string>("errcode")))
        //            {
        //                var ticket = token.Value<string>("ticket");
        //                if (ticket != "")
        //                {
        //                    return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        //                }
        //                else
        //                {
        //                    return string.Empty;
        //                }
        //            }
        //            else
        //            {
        //                return string.Empty;
        //            }
        //        }
        //        else
        //        {
        //            return string.Empty;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.LogHelper.Logger.Write(ex);
        //        return string.Empty;
        //    }
        //}

        //public static Stream CreateAppQRCode(string appid, string secret, string path, int width)
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(appid) && !string.IsNullOrEmpty(secret))
        //        {
        //            string accesstoken = GetAccessToken(appid, secret);
        //            string url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={0}";
        //            Dictionary<string, object> dic = new Dictionary<string, object>();
        //            dic.Add("path", path);
        //            dic.Add("width", width);
        //            dic.Add("is_hyaline", true);
        //            if (!string.IsNullOrEmpty(accesstoken))
        //            {
        //                byte[] buffer = RequestHelper.HttpPostJsonBytes(string.Format(url, accesstoken), dic.ToJsonString());
        //                return StreamExtension.BytesToStream(buffer);
        //            }
        //            else
        //            {
        //                return null;
        //            }
        //        }
        //        else
        //        {
        //            return null;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.LogHelper.Logger.Write(ex);
        //        return null;
        //    }
        //}


        //public static JToken PullUnionInfo(string appid, string secret, string openid)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
        //        url = string.Format(url, accesstoken, openid);
        //        string strUserInfo = RequestHelper.HttpGet(url);
        //        //Logger.LogHelper.Logger.Write("url:" + url + " userinfo:" + strUserInfo + " appid:" + appid);
        //        JToken userinfo = strUserInfo?.JsonToEntity<JToken>();
        //        string errcode = userinfo?.Value<string>("errcode");
        //        if (string.IsNullOrEmpty(errcode))
        //        {
        //            return userinfo;
        //        }
        //        else
        //        {
        //            //Logger.LogHelper.Logger.Write(strUserInfo + " appid:" + appid + " secret:" + secret);
        //            return null;
        //        }
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}
        //public static string SendMessage(string appid, string secret, object param)
        //{
        //    string accesstoken = GetAccessToken(appid, secret);
        //    if (!string.IsNullOrEmpty(accesstoken))
        //    {
        //        string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}";
        //        url = string.Format(url, accesstoken);

        //        string response = RequestHelper.HttpPostJson(url, param.ToJsonString());
        //        //Logger.LogHelper.Logger.Write(response + " " + param.ToJsonString());
        //        return response;
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}

    }
}


public class WechatMenu
{
    public List<WechatMenuButton> button { get; set; }
}

public class WechatMenuButton
{
    public string type { get; set; }
    public string name { get; set; }
    public string key { get; set; }
    public string url { get; set; }
    public string appid { get; set; }
    public string pagepath { get; set; }

    public List<WechatMenuButton> sub_button { get; set; }
}

public class WechatUserInfo
{
    public string openid { get; set; }
    public string unionid { get; set; }
    public string headimgurl { get; set; }
    public string nickname { get; set; }
    public int? sex { get; set; }
    public string city { get; set; }
    public string province { get; set; }
    public string country { get; set; }
}